<!-- 
流程配置查看 DLG
对话框采用属性触发模式,需要在父控件定义变量,对父控件改动较多
调用方式
引入 
  import FlowInfoDlg from "@/components/AIT/FlowInfo";
  components: { FlowInfoDlg },
模板 
  <flow-info-dlg :visible.sync="flowOpen" :code="flowCode" ></flow-info-dlg>
变量 
  flowOpen: false,
方法 
  handleFlowInfo() { this.flowOpen = true; },
-->
<template>
  <div>
    <el-dialog title="流程配置信息" width="80%" :visible.sync="innerVisible" append-to-body>
      <el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="80px" @submit.native.prevent>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="参数编码" prop="flowCode">
              <el-input v-model="form.flowCode" size="small" @keyup.enter.native="handleFlowCode">
                <i slot="suffix" class="el-input__icon el-icon-refresh-right" @click="handleFlowCode"></i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="参数类型" prop="flowType">{{ form.flowType }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文件名称" prop="fileName"> {{ form.fileName }} </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="文件参数" prop="fileParm"> {{ form.fileParm }} </el-form-item>
          </el-col> -->
          <el-col :span="16">
            <el-form-item label="文件路径" prop="filePath"> {{ form.filePath }} </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <pre style="margin-top:-16px;">
              <code style="height: 430px;" class="hljs" v-html="highlightedCode(form.flowText, form.flowType)"/>
            </pre>
          </el-col>
          <el-col :span="6">
            <el-table :data="hisList" ref="hisTable" border @current-change="handleCurrentChange" style="height:430px"
              :row-style="{ height: '32px' }" :cell-style="{ padding: '0px' }" highlight-current-row>
              <el-table-column label="参数清单" prop="flowCode"></el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleOpenFile" icon="el-icon-files" type="warning">打开源文件</el-button>
        <el-button @click="handleCopy" icon="el-icon-copy-document" type="success">拷 贝</el-button>
        <el-tooltip content="依据参数编码,从缓存读取参数信息" placement="top-start" effect="dark">
          <el-button @click="handleFlowCode" icon="el-icon-refresh" type="success">读 取</el-button>
        </el-tooltip>
        <el-button @click="reset" icon="el-icon-delete" type="info">清 空</el-button>
        <el-button @click="cancel" icon="el-icon-circle-close" type="info">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 源文件弹框 -->
    <el-dialog width="80%" title="源文件编辑" :visible.sync="fileVisible" append-to-body>
      <el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="80px" @submit.native.prevent>
        <el-form-item label="文件路径" prop="filePath">{{ form.filePath }}</el-form-item>
        <el-form-item label="文件内容" prop="flowText">
          <el-input type="textarea" :rows="20" v-model="form.fileText" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCopyFile" icon="el-icon-copy-document" type="success">拷 贝</el-button>
        <el-button @click="handlePastFile" icon="el-icon-finished" type="success">粘 贴</el-button>
        <el-button @click="handleSaveFile" icon="el-icon-upload" type="warning">更 新</el-button>
        <el-button @click="fileVisible=false" icon="el-icon-circle-close" type="info">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getFlowInfo, getParmList, saveFlowFile } from '@/api/aitcommon/flowinfo'
// 语法高亮相关
import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/vs2015.css";
hljs.registerLanguage("json", require("highlight.js/lib/languages/json"));
hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));

import copy from 'copy-to-clipboard';
import { throws } from 'assert';


export default {
  name: "FlowInfoDlg",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    code: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 通过外部属性 visible 控制是否显示对话框
      // 因为 visible 不可修改,所以新建 innerVisible 用于控制对话框是否显示
      // 该方式比较麻烦,简单的方式可以创建函数 openDlg 打开对话框,这样不用区分两个属性
      innerVisible: this.visible,
      fileVisible: false,
      loading: false,
      form: {},
      rules: {},
      hisList: [],
    }
  },
  watch: {
    visible(val, oldval) {
      if (val === oldval) {
        return;
      }
      
      this.init();
      this.innerVisible = val;
    },
    code(val, oldval) {
      // console.info('flowCode', val, this.flowCode);
    },
    // 如果内部有新值变化，更新外部visible
    innerVisible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      // 修改父控件 visible 属性
      this.$emit('update:visible', val)
    },
  },
  methods: {
    // 打开源文件
    handleOpenFile() {
      if (!this.form.flowCode) {
        this.msgError('参数变为为空!');
        return;
      }
      //获取源文件文本
      this.fileVisible = true;
      this.loading = true;
      getFlowInfo(this.form.flowCode).then((res) => {
        this.form.fileText = res.data.fileText;
      }).finally(res=>{
        this.loading=false;
      });
    },
    async handleCopyFile() {
      if (this.form.fileText) {
        // copy(this.form.fileText);
        // 这里使用web api,支持浏览器 Chrome、Firefox 和 Safari
        // 参考链接 https://blog.csdn.net/LiChengzhong01/article/details/121557751
        await navigator.clipboard.writeText(this.form.fileText);
        this.$message('内容已拷贝至粘贴板!');
      }
    },
    async handlePastFile() {
      let text = await navigator.clipboard.readText();
      this.form.fileText = text;
      this.$message('内容已粘贴!');
    },
    handleSaveFile() {
      this.$confirm('此操作将保存源文件并刷新配置, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 保存文件
        saveFlowFile(this.form.filePath, this.form.fileText).then(res => {
          //刷新flowinfo
          return this.handleFlowCode();
        }).then(res => {
          //刷新参数列表
          return this.handleParmList();
        }).then(res => {
          //关闭源文件弹窗
          this.fileVisible = false;
          this.msgSuccess('源文件保存成功,配置信息刷新!');
        })
      });
    },
    /** 高亮显示 */
    highlightedCode(text, type) {
      let ret = {};
      // 标准语法高亮
      if (type === 'json') {
        ret = hljs.highlight('json', text || "");
      } else if (type === 'sql') {
        ret = hljs.highlight('sql', text || "")
      } else {
        ret = ''
      }

      // 添加自定义格式
      let retStr = ret.value || '&nbsp;';
      // 使用正则表达式替换,为${}变量增加样式flow-parm
      let retStr1 = retStr.replaceAll(/\${(.*?)}/g, '<span class="flow-parm">${$1}</span>')
      // console.info('retStr1',retStr1);
      return retStr1;
    },

    init() {
      if (this.visible && this.code) {
        this.reset();
        this.form.flowCode = this.code
        this.handleFlowCode();
      }
    },
    
    handleCurrentChange(row) {
      // console.info('handleCurrentChange', row.flowCode)
      if (row) {
        this.form.flowCode = row.flowCode;
        this.handleFlowCode();
      }
    },

    cancel() {
      this.reset();
      this.innerVisible = false;
    },
    reset() {
      this.form = {};
      this.hisList = [];
      this.resetForm("form");
    },
    handleCopy() {
      if (this.form.flowText) {
        copy(this.form.flowText);
        this.$message('内容已拷贝至粘贴板!');
      }
    },

    handleFlowCode(){
      // this.loading=true;
      this.getFlowInfo().then(() => {
          this.getParmList();
        }).finally(res=>{
          // this.loading=false;
        })
    },

    getFlowInfo() {
      // 将函数封装成Promise,支持顺序调用
      return new Promise((resolve, reject) => {
        if (this.form.flowCode) {
          this.loading = true;
          getFlowInfo(this.form.flowCode).then((res) => {
            this.form = {
              flowCode: this.form.flowCode,
              flowText: res.data.value,
              flowType: res.data.type,
              fileName: res.data.fileName,
              filePath: res.data.filePath,
              fileParm: res.data.fileParm,
              fileText: res.data.fileText,
            }
            // 强制刷新界面
            // this.$forceUpdate()
            // 将当前flowCode添加到参数列表中
            let has = this.hisList.find(item => item.flowCode === this.form.flowCode)
            if (!has)
              this.hisList.push({ flowCode: this.form.flowCode });
            this.loading = false;
          }).finally(() => {
            this.loading = false;
            // 通过resolve返回
            resolve();
          })
        }

      })
    },
    getParmList() {
      // 将函数封装成Promise,支持顺序调用
      return new Promise((resolve, reject) => {
        if (this.form.flowCode) {
          this.loading = true;
          // 获取当前flow内部变量
          getParmList(this.form.flowCode).then(res => {
            // console.info('handleParmList',res.data)
            // 将获取的内部变量添加到现有变量清单的尾部
            res.data.forEach(item => {
              let has = this.hisList.find(item1 => item1.flowCode === item)
              if (!has) {
                // 添加到数组尾部
                this.hisList.push({ flowCode: item });
              }
            })
          }).finally(() => {
            this.loading = false;
            // 通过resolve返回
            resolve();
          })
        }
      })
    }
  }
}

</script>

<style lang="scss" scoped>

</style>
